
import React from "react";
import { ToolType } from "../constants/ToolType";
import { useAnimate } from "tools/hooks/useAnimate";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import Controller from "../Controller";

/** 摄像头 轨道（球形轨道） */
export default function useControls(controller: Controller) {

    /** 启动模式 */
    const model = controller.useMemo(s => s.model, []);

    /** 轨道控制器 */
    const controls = controller.useMemo(s => s.controls, []);

    /** 摄像机 */
    const camera = controller.useMemo(s => s.camera, []);

    /** 摄像机 */
    const renderer = controller.useMemo(s => s.renderer, []);

    /** 选中得工具 */
    const selectedTool = controller.useMemo(s => s.selectedTool, []);

    React.useEffect(() => {
        if (!camera || !renderer || model === 'preview') {
            controller.run(async s => { 
                s.controls?.dispose();
                s.controls = undefined;
            })
        } else {
            controller.run(async s => { s.controls = new OrbitControls(camera, renderer.domElement) })
        }
    }, [controller, camera, renderer, model])

    // 选择了摄像机工具
    React.useEffect(() => {
        if (controls) {
            controls.enabled = selectedTool === ToolType.摄像机 || selectedTool === ToolType.选取;
        }
    }, [controls, selectedTool])

    useAnimate(React.useCallback(() => {
        if (!controls) return;
        controls.update();
    }, [controls]))
}